package com.kpmg.datalake.reportanalysis.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.common.constants.Constants;
import com.kpmg.datalake.common.dao.CompanyInfoMapper;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDS;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDataSourceContextHolder;
import com.kpmg.datalake.common.enums.MultiDimTypeEnum;
import com.kpmg.datalake.common.enums.VbaProjectTypeEnum;
import com.kpmg.datalake.common.model.DimInfo;
import com.kpmg.datalake.common.model.ProjectRptSql;
import com.kpmg.datalake.common.service.CommonExecuteService;
import com.kpmg.datalake.common.service.IPrjRptSqlMpngService;
import com.kpmg.datalake.common.service.impl.ProjectRptSqlServiceImpl;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.utils.Utils;
import com.kpmg.datalake.common.vo.GeneralHeaderVO;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.reportanalysis.dao.ReportMapper;
import com.kpmg.datalake.reportanalysis.service.ReportService;
import com.kpmg.datalake.reportanalysis.vo.MultiDimRequestVO;
import com.kpmg.datalake.reportanalysis.vo.ReportTemplateVO;
import com.kpmg.datalake.reportanalysis.vo.TableHeaderVO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 报表相关操作服务
 *
 * @author Tony
 */
@Service
public class ReportServiceImpl implements ReportService {

  // 日志
  private static final Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);
  // 注入服务
  @Autowired
  private ReportMapper reportMapper;

  @Autowired
  private IPrjRptSqlMpngService iPrjRptSqlMpngService;

  // 常量信息
  private static final int INITIAL_SIZE = 16;
  private String sbjCdField = "SBJ_CD";
  private String sbjNmField = "SBJ_NM";
  private String deptCdField = "DEPT_CD";
  private String deptNmField = "DEPT_NM";
  private String deptPrt = "deptPrt";
  private String deptLvl = "deptLvl";
  private String cstCdField = "CST_CD";
  private String cstNmField = "CST_NM";
  private String cstPrt = "cstPrt";
  private String cstLvl = "cstLvl";
  private String prjCdField = "PRJ_CD";
  private String prjNmField = "PRJ_NM";
  private String prjPrt = "prjPrt";
  private String prjLvl = "prjLvl";
  private String amtBop = "amtBop";
  private String amtDptAcm = "amtDptAcm";
  private String amtCrAcm = "amtCrAcm";
  private String amtEop = "amtEop";
  private String sbjLvlField = "SBJ_LVL";
  private String andField = " and ";
  private String smyRcrdId = "smyRcrdId";
  private String smyRcrdNm = "smyRcrdNm";
  private String smyRcrdIdField = "SMY_RCRD_ID";
  private String smyRcrdNmField = "SMY_RCRD_NM";
  private String pageNo = "PAGE_NO";
  private String acgYr = "ACG_YR";
  private String acgMo = "ACG_MO";
  private String startDate = "SALE_DT_BGN";
  private String endDate = "SALE_DT_END";
  private String corpCd = "CORP_CD";
  private String dimTpCd = "DIM_TP_CD";
  private String corpNm = "CORP_NM";
  private String acgMoEnd = "ACG_MO_END";
  private String prmsnCd = "PRMSN_CD";
  private String sbjLvl = "sbjLvl";
  private String localUpdateKey = "1";
  private String crtUsrId = "CRT_USR_ID";
  private static final String SBJ_FLAG = "SBJ";
  private static final String HAS_LEVEL_FLAG = "hasLevel";

  /**
   * 初始化科目
   */
  @Override
  @DynamicDS("projectId")
  public ServerResponse<PageInfo<DimInfo>> initSbj(int page, int size, String projectId,
      String param) {
    try {
      // 分页查询科目
      if (size != -1) {
        PageHelper.startPage(page, size);
      }
      List<DimInfo> result = reportMapper.initSbj(param);
      PageInfo<DimInfo> pageInfo = new PageInfo<>(result);
      return ServerResponse.createBySuccess("初始化科目成功！", pageInfo);
    } catch (Exception e) {
      logger.error("初始化科目时异常:{}", e.getMessage(), e);
      return ServerResponse.createByErrorMessage("初始化科目失败，异常:" + e.getMessage());
    }
  }



  /**
   * 获取用户历史模板
   */
  @Override
  @DynamicDS("projectId")
  public ServerResponse<PageInfo<Map<String, Object>>> getUserRptTemplates(String userId,
      String projectId,
      String filter, int page, int size) {
    try {
      List<Map<String, Object>> templates = new ArrayList<>();
      if (size != -1) {
        PageHelper.startPage(page, size);
      }
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

      // 获取条件信息记录
      List<Map<String, Object>> templateRecords = reportMapper.queryUserTemplates(userId, filter);
      PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(templateRecords);
      return ServerResponse.createBySuccess("获取历史报表成功！", mapPageInfo);
    } catch (Exception e) {
      logger.error("获取历史报表时异常:{}", e.getMessage(), e);
      return ServerResponse.createByErrorMessage("获取历史报表失败，异常:" + e.getMessage());
    }
  }

  /**
   * 保存报表筛选条件
   */
  @DynamicDS("projectId")
  @Override
  public ServerResponse<String> saveCondition(String projectId, ReportTemplateVO vo) {
    try {
      String smyRcrdIdRtn = null;
      Map<String, String> param = new HashMap<>();
      // 项目名称
      param.put(pageNo, String.valueOf(vo.getPageNum()));
      param.put("SMY_RCRD_NM", vo.getTemplateNm());
      param.put("PRMSN_CD", vo.getPrmsnCd());
      param.put("ACG_YR", vo.getYear());
      param.put("ACG_MO", vo.getBeginMonth());
      param.put("ACG_MO_END", vo.getEndMonth());
      param.put("CORP_CD", vo.getCorpCd());
      param.put("CORP_NM", vo.getCorpNm());
      param.put("CRT_USR_ID", ContextHolderUtils.getLoginUser().getUsrId());
      param.put("RMRK", vo.getRemark());

      param.put("SALE_DT_BGN", vo.getStartDate());
      param.put("SALE_DT_END", vo.getEndDate());
      param.put("SBJ_CD", vo.getSbjCd());
      param.put("SBJ_NM", vo.getSbjNm());
      param.put("PAGE_NO", String.valueOf(vo.getPageNum()));

      Map<String, String> auxDim = vo.getAuxDim();
      int size = auxDim.size() / 3;
      for (int i = 1; i <= size; i++) {
        param.put("SEG" + i + "_CD", auxDim.get("SEG" + i + "_CD"));
        param.put("SEG" + i + "_NM", auxDim.get("SEG" + i + "_NM"));
      }

      // 创建用户ID
      param.put(crtUsrId, ContextHolderUtils.getLoginUser().getUsrId());
      //if (localUpdateKey.equals(vo.getUpdateKey())) {
      // 更新操作
      if (!StringUtils.isEmpty(vo.getSmyRcrdId())) {
        // 更新操作
        //smyRcrdIdRtn = vo.getSmyRcrdId();
        Map<String, String> keyMap = new HashMap<>(INITIAL_SIZE);
        keyMap.put(smyRcrdIdField, vo.getSmyRcrdId());
        // 更新报表筛选条件
        reportMapper.updateData(Constants.SAVE_SMY_RCRD_TBL_NM, param, keyMap);
        // 删除维度展开状态表
        //reportMapper.deleteData(Constants.SAVE_DIM_DRILL_TBL_NM, keyMap);
        // }
      } else {
        // 2. 新增操作
        // 查询主键
        smyRcrdIdRtn = Utils.getGUID();
        param.put(smyRcrdIdField, smyRcrdIdRtn);
        // 保存报表筛选条件
        reportMapper.insertData(Constants.SAVE_SMY_RCRD_TBL_NM, param);
      }
      //saveConitionExp(vo, smyRcrdIdRtn, param);
      return ServerResponse.createBySuccess("保存报表筛选条件成功！", smyRcrdIdRtn);
    } catch (Exception e) {
      logger.error("保存报表筛选条件时异常:{}", e.getMessage(), e);
      return ServerResponse.createByErrorMessage("保存报表筛选条件失败，异常:" + e.getMessage());
    }
  }

  /**
   * 删除用户历史模板
   */
  @DynamicDS("projectId")
  @Transactional
  @Override
  public ServerResponse<String> delUserTemplate(String projectId, String smyId) {
    try {
      Map<String, String> keyMap = new HashMap<>(INITIAL_SIZE);
      keyMap.put(smyRcrdIdField, smyId);
      // 删除维度展开状态表
      //reportMapper.deleteData(Constants.SAVE_DIM_DRILL_TBL_NM, keyMap);
      // 删除报表筛选条件
      reportMapper.deleteData(Constants.SAVE_SMY_RCRD_TBL_NM, keyMap);
      return ServerResponse.createBySuccess("删除用户历史模板成功！", "success");
    } catch (Exception e) {
      logger.error("删除用户历史模板时异常:{}", e.getMessage(), e);
      return ServerResponse.createByErrorMessage("删除用户历史模板失败，异常:" + e.getMessage());
    }
  }

  @Autowired
  private ProjectRptSqlServiceImpl projectRptSqlService;

  @Autowired
  private CommonExecuteService commonExecuteService;

  @Autowired
  private CompanyInfoMapper companyInfoMapper;

  /**
   * 查询多维分析数据
   */
  @Override
  public Page<Map<String, Object>> getMultiDimReportData(MultiDimRequestVO requestVO) {
    Map<String, Object> paramMap = new HashMap<>();

    // 构建初始化参数
    initBaseParamMap(requestVO, paramMap);

    // 切换com库，查询是否是集团公司
    DynamicDataSourceContextHolder.setDataSourceType(requestVO.getProjectId());
    String groupCompany = "";
    try {
      // 判断是集团公司，还是单公司
      groupCompany = companyInfoMapper.isGroupCompany(requestVO.getCorpCd());
    } finally {
      DynamicDataSourceContextHolder.clearDataSource();
    }

    // 1. 判断是集团还是单公司,设置查询的科目信息表
    if (StringUtils.isEmpty(groupCompany)) {
      // 集团科目表
      paramMap.put("Sbj_tbl", "MDA_DIM_SBJ");
    } else {
      // 单公司科目表
      paramMap.put("Sbj_tbl", "MDA_SBJ_CORP WHERE CORP_CD = " + "'" + requestVO.getCorpCd() + "'");
    }

    String sqlTextByInfo = "";
    Page<Map<String, Object>> result = null;
    // 实例化分页对象
    Page<Map<String, Object>> page = new Page<>(requestVO.getPageNum(), requestVO.getPageSize());
    // 2. 判断是普通查询还是钻取查询
    if (StringUtils.isEmpty(requestVO.getClickFlag())) {
      // 2.1 普通查询
      this.generalQueryData(requestVO.getAuxDim(), requestVO.getSbjCd(), requestVO.getSbjNm(),
          requestVO.getSbjLevel(),
          paramMap);

      sqlTextByInfo = projectRptSqlService.getSqlTextByInfo(requestVO.getProjectId(),
          MultiDimTypeEnum.MULTI_DIM_TYPE_QUERY.getCode());

      result = commonExecuteService
          .queryPageByMap(requestVO.getProjectId(), page, sqlTextByInfo, paramMap);

      // 2.2 获取查询出的数据
      List<Map<String, Object>> records = result.getRecords();

      // 2.3 重新组装数据，返回给前端
      assembleResult(requestVO.getAuxDim(), records, requestVO.getClickFlag(),
          requestVO.getSbjLevel());

      // 2.4 配置分页信息
      result.setRecords(records);
    } else {
      // 3 钻取查询
      // 3.1 判断钻取的维度
      if (SBJ_FLAG.equals(requestVO.getClickFlag())) {
        // 获取执行sql对象，并判断此项目的科目维度是否有层次
        ProjectRptSql projectRptSqlByInfo = projectRptSqlService
            .getProjectRptSqlByInfo(requestVO.getProjectId(),
                MultiDimTypeEnum.MULTI_DIM_TYPE_QUERY.getCode());
        if (projectRptSqlByInfo != null && HAS_LEVEL_FLAG
            .equals(projectRptSqlByInfo.getRptExpType())) {
          sqlTextByInfo = projectRptSqlByInfo.getSqlTxt();
          // 3.1.1 科目维度钻取
          this.subjectDrill(requestVO.getAuxDim(), requestVO.getSbjCd(), requestVO.getSbjLevel(),
              paramMap);
        } else {
          return new Page<>();
        }
      } else {
        // 3.1.2 辅助核算维度钻取
        sqlTextByInfo = projectRptSqlService.getSqlTextByInfo(requestVO.getProjectId(),
            MultiDimTypeEnum.MULTI_DIM_TYPE_DRILL.getCode());
        this.auxDrill(requestVO.getAuxDim(), requestVO.getSbjCd(), requestVO.getSbjNm(),
            requestVO.getClickFlag(), paramMap);
      }

      result = commonExecuteService
          .queryPageByMap(requestVO.getProjectId(), page, sqlTextByInfo, paramMap);
      // 3.2 获取查询出的数据
      List<Map<String, Object>> records = result.getRecords();
      // 3.3 重新组装数据，返回给前端
      assembleResult(requestVO.getAuxDim(), records, requestVO.getClickFlag(),
          requestVO.getSbjLevel());

      result.setRecords(records);
    }

    return result;
  }

  /**
   * 组装响应数据，返回给客户端
   */
  private void assembleResult(Map<String, String> requestMap, List<Map<String, Object>> records,
      String clickFlag, String sbjLevel) {
    // 循环索引下标
    int size = requestMap.size() / 3;

    for (Map<String, Object> item : records) {
      for (int i = 1; i <= size; i++) {
        if (item.get("SEG" + i + "_CD") == null) {
          if (!StringUtils.isEmpty(requestMap.get("SEG" + i + "_CD"))) {
            item.put("SEG" + i,
                requestMap.get("SEG" + i + "_CD") + "-" + requestMap.get("SEG" + i + "_NM"));
            item.put("SEG" + i + "_CD", requestMap.get("SEG" + i + "_CD"));
          } else {
            item.put("SEG" + i, requestMap.get("SEG" + i + "_NM"));
            item.put("SEG" + i + "_CD", "");
          }
          item.put("SEG" + i + "_NM", requestMap.get("SEG" + i + "_NM"));
        } else {
          item.put("SEG" + i, item.get("SEG" + i + "_CD") + "-" + item.get("SEG" + i + "_NM"));
          item.put("SEG" + i + "_CD", item.get("SEG" + i + "_CD"));
          item.put("SEG" + i + "_NM", item.get("SEG" + i + "_NM"));
        }
      }
      // 钻取的是科目维度
      if (clickFlag.equals("SBJ")) {
        item.put("SBJ_LVL", String.valueOf(Integer.parseInt(sbjLevel) + 1));
      } else {
        // 普通查询设置科目层级为1
        item.put("SBJ_LVL", StringUtils.isEmpty(sbjLevel) ? 1 : sbjLevel);
      }
      item.put("SBJ", item.get("SBJ_CD") + "-" + item.get("SBJ_NM"));
    }

  }

  /**
   * 普通查询sql的拼接替换
   */
  private Map<String, Object> generalQueryData(Map<String, String> requestMap, String sbjCd,
      String sbjNm, String sbjLvl, Map<String, Object> paramMap) {
    int size = requestMap.size() / 3;
    StringBuilder dril_seg_whr = new StringBuilder("");
    if (StringUtils.isEmpty(sbjLvl)) {
      sbjLvl = "1";
    }
    paramMap.put("Sbj_lvl", " And Sbj_Lvl = '" + sbjLvl + "'");
    paramMap.put("pre_sbj_lvl", " where Pre.Sbj_Lvl = '" + sbjLvl + "'");

    paramMap.put("dril_amt", " Amt_Bop, AMT_DBT_ACM, AMT_CR_ACM, Amt_Eop");
    // 所有维度值都为空, 普通查询
    if (StringUtils.isEmpty(sbjCd) && checkMap(requestMap, size)) {
      for (int i = 1; i <= size; i++) {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Null ").append(" AND ")
            .append("SEG" + i + "_NM").append(" Is Null ");
      }
      paramMap.put("dril_seg_whr", dril_seg_whr.toString());

      return paramMap;
    }

    String code = "";
    String name = "";
    if (!StringUtils.isEmpty(sbjCd) && !StringUtils.isEmpty(sbjNm)) {
      dril_seg_whr.append(" AND SBJ_CD like '" + sbjCd + "%'");
      // 拼接where条件
      StringBuilder cond_whr = new StringBuilder("");
      cond_whr.append(" WHERE Sbj_Nm =").append("'").append(sbjNm).append("'")
          .append(" And Sbj_Cd =").append("'").append(sbjCd).append("'");
      paramMap.put("cond_whr", cond_whr.toString());
    }
    for (int i = 1; i <= size; i++) {
      code = requestMap.get("SEG" + i + "_CD");
      name = requestMap.get("SEG" + i + "_NM");
      // 含有维度信息的情况
      if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(name)) {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD=").append("'").append(code).append("'")
            .append(" AND ").append("SEG" + i + "_NM=").append("'").append(name).append("'");
      } else {
        // 携带header条件的普通查询
        // dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Not Null ").append(" AND ").append("SEG" + i + "_NM").append(" Is Not Null ");
        if (!checkMap(requestMap, size)) {
          dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Not Null ")
              .append(" AND ").append("SEG" + i + "_NM").append(" Is Not Null ");
        } else {
          dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Null ").append(" AND ")
              .append("SEG" + i + "_NM").append(" Is Null ");
        }

      }
    }
    paramMap.put("dril_seg_whr", dril_seg_whr.toString());

    return paramMap;
  }

  /**
   * 遍历map,判断是否value全部为空
   */
  private boolean checkMap(Map<String, String> requestMap, int size) {
    for (int i = 1; i <= size; i++) {
      if (!StringUtils.isEmpty(requestMap.get("SEG" + i + "_CD"))) {
        return false;
      }
    }
    return true;
  }

  /**
   * 辅助核算维度钻取sql拼接替换
   */
  private Map<String, Object> auxDrill(Map<String, String> requestMap, String sbjCd, String sbjNm,
      String clickDim, Map<String, Object> paramMap) {
    int size = requestMap.size() / 3;

    StringBuilder seg_all = new StringBuilder("");
    StringBuilder dril_seg_whr = new StringBuilder("");
    StringBuilder dril_seg_grp = new StringBuilder("");
    StringBuilder dril_seg_sel = new StringBuilder("");
    String code = "";
    String name = "";
    dril_seg_sel.append("'").append(sbjCd).append("'").append(" Sbj_Cd, ").append("'").append(sbjNm)
        .append("'").append(" Sbj_Nm,");
    dril_seg_whr.append(" And instr(SBJ_CD,'"+ sbjCd +"')=1")
        .append(" And Sbj_Nm Is Not Null And Sbj_Lvl Is Not Null");
    for (int i = 1; i <= size; i++) {
      code = requestMap.get("SEG" + i + "_CD");
      name = requestMap.get("SEG" + i + "_NM");
      seg_all.append(",SEG" + i + "_CD").append(",SEG" + i + "_NM");
      // 含有维度信息的情况
      if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(name)) {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD=").append("'").append(code).append("'")
            .append(" AND ").append("SEG" + i + "_NM=").append("'").append(name).append("'");
        dril_seg_sel.append("'").append(code).append("'").append(" SEG" + i + "_CD,").append("'")
            .append(name).append("'").append(" SEG" + i + "_NM,");
      } else {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Not Null ")
            .append(" AND ").append("SEG" + i + "_NM").append(" Is Not Null ");
        // 如果某个维度被钻取了
        if (clickDim.equals("SEG" + i)) {
          dril_seg_sel.append(" SEG" + i + "_CD,").append(" SEG" + i + "_NM,");
          continue;
        }
        dril_seg_sel.append("'").append(code).append("'").append(" SEG" + i + "_CD,").append("'")
            .append(name).append("'").append(" SEG" + i + "_NM,");
      }

    }

    dril_seg_grp.append(" Group By ").append(clickDim + "_CD,").append(clickDim + "_NM");
    paramMap.put("seg_all", seg_all.toString());
    paramMap.put("dril_seg_whr", dril_seg_whr.toString());
    paramMap.put("dril_seg_grp", dril_seg_grp.toString());
    // 去除字符串最后一个,号
    paramMap.put("dril_seg_sel",
        dril_seg_sel.toString().substring(0, dril_seg_sel.toString().length() - 1));
    return paramMap;
  }

  /**
   * 科目维度钻取sql拼接替换
   */
  private Map<String, Object> subjectDrill(Map<String, String> requestMap, String sbjCd,
      String sbjLevel, Map<String, Object> paramMap) {
    int size = requestMap.size() / 3;

    StringBuilder dril_seg_sel = new StringBuilder("");
    StringBuilder dril_sbj_cd = new StringBuilder("");
    StringBuilder dril_seg_whr = new StringBuilder("");
    StringBuilder dril_seg_grp = new StringBuilder("");
    StringBuilder Sbj_lvl = new StringBuilder("");
    StringBuilder Sbj_cd_whr = new StringBuilder("");
    StringBuilder cond_whr = new StringBuilder("");

    sbjLevel = String.valueOf(Integer.parseInt(sbjLevel) + 1);
    cond_whr.append(" where 1 = 1 ");
    dril_sbj_cd.append("Substr(Sbj_Cd, 0, (").append(sbjLevel).append(" - 1) * 2 + 4)");
    dril_seg_grp.append("Group By Substr(Sbj_Cd, 0, (").append(sbjLevel).append(" - 1) * 2 + 4)");
    Sbj_lvl.append("And Sbj_Lvl = ").append("'").append(sbjLevel).append("'");
    Sbj_cd_whr.append(" And instr(SBJ_CD,'"+ sbjCd +"')=1");
    dril_seg_whr.append(" And instr(SBJ_CD,'"+ sbjCd +"')=1");
    String code = "";
    String name = "";
    for (int i = 1; i <= size; i++) {
      code = requestMap.get("SEG" + i + "_CD");
      name = requestMap.get("SEG" + i + "_NM");
      // 含有维度信息的情况
      if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(name)) {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD=").append("'").append(code).append("'")
            .append(" AND ").append("SEG" + i + "_NM=").append("'").append(name).append("'");
        cond_whr.append(" AND ").append("SEG" + i + "_CD=").append("'").append(code).append("'")
            .append(" AND ").append("SEG" + i + "_NM=").append("'").append(name).append("'");
        dril_seg_sel.append(" ,SEG" + i + "_CD,").append(" SEG" + i + "_NM");
        dril_seg_grp.append(" ,SEG" + i + "_CD,").append(" SEG" + i + "_NM");
      } else {
        dril_seg_whr.append(" AND ").append("SEG" + i + "_CD").append(" Is Not Null ")
            .append(" AND ").append("SEG" + i + "_NM").append(" Is Not Null ");
      }
    }

    paramMap.put("dril_seg_whr", dril_seg_whr.toString());
    paramMap.put("dril_seg_grp", dril_seg_grp.toString());
    paramMap.put("dril_seg_sel", dril_seg_sel.toString());
    paramMap.put("dril_sbj_cd", dril_sbj_cd.toString());
    paramMap.put("Sbj_cd_whr", Sbj_cd_whr.toString());
    paramMap.put("Sbj_lvl", Sbj_lvl.toString());
    paramMap.put("cond_whr", cond_whr.toString());
    paramMap.put("dril_amt",
        " sum(Amt_Bop) Amt_Bop, sum(AMT_DBT_ACM) AMT_DBT_ACM, sum(AMT_CR_ACM) AMT_CR_ACM, sum(Amt_Eop) Amt_Eop");
    return paramMap;
  }

  /**
   * 初始化请求参数
   */
  private void initBaseParamMap(MultiDimRequestVO requestVO, Map<String, Object> paramMap) {
    paramMap.put("corp_cd", "'" + requestVO.getCorpCd() + "'");
    paramMap.put("year", "'" + requestVO.getYear() + "'");
    paramMap.put("begin_month", "'" + requestVO.getBeginMonth() + "'");
    paramMap.put("end_month", "'" + requestVO.getEndMonth() + "'");
  }

  @Override
  public ArrayList<TableHeaderVO> getMultiHeader(String projectId) {
    List<GeneralHeaderVO> generalHeaderVOS = iPrjRptSqlMpngService
        .selectGeneralHeader(projectId, VbaProjectTypeEnum.MULTIDIMENSIONAL_REPORT.getCode(), null);
    return assembleHeader(generalHeaderVOS);
  }

  @Override
  @DynamicDS("projectId")
  public ServerResponse<PageInfo<DimInfo>> initAuxDim(int page, int size, String projectId,
      String param, String tableName) {
    try {
      // 分页查询科目
      if (size != -1) {
        PageHelper.startPage(page, size);
      }
      List<DimInfo> result = reportMapper.queryOtherDim(tableName, param);
      PageInfo<DimInfo> pageInfo = new PageInfo<>(result);
      return ServerResponse.createBySuccess("初始化辅助核算成功！", pageInfo);
    } catch (Exception e) {
      logger.error("初始化辅助核算时异常:{}", e.getMessage(), e);
      return ServerResponse.createByErrorMessage("初始化辅助核算失败，异常:" + e.getMessage());
    }
  }

  /**
   * 组装动态表头
   */
  private ArrayList<TableHeaderVO> assembleHeader(List<GeneralHeaderVO> headerVOList) {
    ArrayList<TableHeaderVO> headerList = new ArrayList<>();
    for (GeneralHeaderVO item : headerVOList) {
      TableHeaderVO tableHeaderVO = new TableHeaderVO();
      tableHeaderVO.setIsDim(item.getFmtCd());
      tableHeaderVO.setCname(item.getFldNm());
      tableHeaderVO.setOrderNum(item.getDsplOrdr());
      tableHeaderVO.setPropName(item.getClmnCd());
      // 科目维度列
      if (tableHeaderVO.getOrderNum() == 0) {
        tableHeaderVO.setTableName("MDA_DIM_SBJ");
      } else {
        // 是否是维度列
        if (item.getFmtCd().equals("1")) {
          // 设置辅助核算列
          tableHeaderVO.setTableName("MDA_DIM_SEG" + item.getDsplOrdr());
        }
      }
      headerList.add(tableHeaderVO);
    }
    return headerList;
  }

}
